# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)

# helper ----
source('../00_custom_functions.R')

# data ----
state <- "WA"
ppmf19 <- read_ppmf(state, "../../data-raw/ppmf_19.csv")
ppmf12 <- read_ppmf(state, "../../data-raw/ppmf_12.csv")
ppmf4 <- read_ppmf(state, "../../data-raw/ppmf_04.csv")

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf19) <- paste("v19", colnames(ppmf19), sep = "_")
ppmf19 <- ppmf19 %>% rename(GEOID = v19_GEOID)

ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf12) <- paste("v12", colnames(ppmf12), sep = "_")
ppmf12 <- ppmf12 %>% rename(GEOID = v12_GEOID)

ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf4) <- paste("v4", colnames(ppmf4), sep = "_")
ppmf4 <- ppmf4 %>% rename(GEOID = v4_GEOID)

# comparison ----
census <- create_block_table(state = state)

# all joined ----
mega <- census %>%
  left_join(ppmf12, by = 'GEOID') %>%
  left_join(ppmf4, by = 'GEOID') %>% 
  left_join(ppmf19, by = "GEOID")

# and remove duplicates
mega <- mega %>% select(-contains('.'))
# and set missing block pop/vap to 0
mega[is.na(mega)] <- 0
# add block_group back (dropped by contains('.'))
mega <- mega %>% breakdown_geoid()

# from VEST 2018
prec <- st_read('../../data/WA/wa_2018/wa_2018.shp')
prec <- prec %>% st_transform(st_crs(mega))

# Get Census Shapes :
sld_low <- tigris::state_legislative_districts('WA', 'lower')
sld_up <- tigris::state_legislative_districts('WA', 'upper')
cd <- tigris::congressional_districts('WA')


# Align ppmf & precincts:
block_prec_match <- geo_match(from = mega, to = prec, method = 'centroid')
prec_low_match <- geo_match(from = prec, to = sld_low, method = 'centroid')
prec_up_match <- geo_match(from = prec, to = sld_up, method = 'centroid')
prec_cd_match <- geo_match(from = prec, to = cd, method = 'centroid')

prec <- prec %>% mutate(
  sld_low = sld_low$SLDLST[prec_low_match],
  sld_up = sld_up$SLDUST[prec_up_match],
  cd = cd$CD116FP[prec_cd_match]
)

mega$prec <- block_prec_match
ppmf_at_prec <- ppmf_block2prec(mega, prec)


# join them together
wa <- prec %>%
  mutate(prec = row_number()) %>%
  left_join(ppmf_at_prec, by = 'prec')

wa$cd <- as.numeric(wa$cd)
wa$sld_low <- as.numeric(wa$sld_low)
wa$sld_up <- as.numeric(wa$sld_up)
wa <- wa %>% mutate(row_id = row_number())
saveRDS(wa, '../../data/WA/wa.Rds', compress = 'xz')
